<template>
	<div class="login">
		<div class="wrapper">
			<h2>WEB ADMIN</h2>
			<el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="80px" class="demo-ruleForm">
				<el-form-item label="账号" prop="username">
					<el-input v-model="ruleForm.username"></el-input>
				</el-form-item>
				<el-form-item label="密码" prop="password">
					<el-input v-model="ruleForm.password" type="password"></el-input>
				</el-form-item>
				<el-form-item align="right">
					<el-button type="primary" @click="submitForm('ruleForm')">登录</el-button>
					<el-button @click="resetForm('ruleForm')">重置</el-button>
				</el-form-item>
			</el-form>
		</div>
	</div>
</template>

<script>
	import {
		mapMutations
	} from 'vuex'
	/* 第四步 */
	import {
		initDnameicRoutes
	} from '../router/index.js'
	export default {
		name: 'Login',
		data() {
			return {
				ruleForm: {
					username: 'admin',
					password: 'admin',
				},
				rules: {
					username: [{
							required: true,
							message: '请输入账号',
							trigger: 'blur'
						},
						{
							min: 5,
							max: 10,
							message: '长度在 5 到 10 个字符',
							trigger: 'blur'
						}
					],
					password: [{
							required: true,
							message: '请输入密码',
							trigger: 'blur'
						},
						{
							min: 5,
							max: 10,
							message: '长度在 5 到 10 个字符',
							trigger: 'blur'
						}
					],
				}
			};
		},
		methods: {
			...mapMutations(['getLogin']),
			submitForm(formName) {
				this.$refs[formName].validate((valid) => {
					if (valid) {
						this.$Api.login({
							username: this.ruleForm.username,
							password: this.ruleForm.password
						}).then(res => {
							console.log(res);
							window.sessionStorage.setItem('token', res.data.token)
							this.$router.push('/') //跳转到首页
							this.getLogin(res.data)
							/* 第五步 */
							initDnameicRoutes()
						})
					} else {
						console.log('error submit!!');
						return false;
					}
				});
			},
			resetForm(formName) {
				this.$refs[formName].resetFields();
			}
		}

	}
</script>

<style scoped>
	.login {
		width: 100%;
		height: 100%;
		background-color: #42B983;
		position: absolute;
		top: 0;
		bottom: 0;
	}

	.wrapper {
		width: 520px;
		height: 260px;
		background-color: #fff;
		padding: 30px;
		margin: 100px auto 0 auto;
	}

	.wrapper h2 {
		color: #333;
		text-align: center;
		padding: 0 0 20px 0;
	}
</style>
